package com.shumi.rbac.web;

import com.shumi.fun.WebResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;


@Slf4j
@RequestMapping("/file")
@RestController
public class FileController {
    WebResult webResult;

    @RequestMapping("/upload")
    public WebResult upload(@RequestParam("file") MultipartFile file) {
        webResult = new WebResult();
        if (!file.isEmpty()) {
            try {
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(new File(file.getOriginalFilename())));
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                log.error(e.getMessage());
                webResult.setResultMsg("上传失败," + e.getMessage());
                return webResult;
            } catch (IOException e) {
                log.error(e.getMessage());
                webResult.setResultMsg("上传失败," + e.getMessage());
                return webResult;
            }
        } else {
            webResult.setResultMsg("上传失败，文件不能为空");
            return webResult;
        }
        webResult.setSuccess(true);
        webResult.setResultMsg("文件上传成功");
        return webResult;
    }


}
